package com.wish233.wiliwilivideo.utils;

import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.transfer.*;
import com.wish233.wiliwilivideo.config.CosManager;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.wish233.wiliwilicommon.constants.RedisConstants.VIDEO_UPDATE;
import static com.wish233.wiliwilicommon.constants.RedisConstants.VIDEO_UPDATE_TTL;

/**
 * 腾讯云cos上传工具类
 *
 * @author WHH
 */
@Component
public class UploadUtil {

    @Resource
    private CosManager cosManager;
    @Resource
    private COSClient cosClient;
    @Resource
    private TransferManager transferManager;
    @Resource
    private StringRedisTemplate stringRedisTemplate;



    /**
     * 上传简单图片 大小不超过20M
     *
     * @return
     */
    public PutObjectResult simplePut(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosManager.getBucket(), key,
                new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     *
     * @param key  唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult simplePut(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosManager.getBucket(), key,
                file);
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 关闭transferManager
     */
    public void shutdownTransferManager() {
        // 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
        // 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
        transferManager.shutdownNow(true);
    }


    // 上传对象
    public void upload(String key, File file)
            throws CosServiceException, CosClientException, InterruptedException {

        // 设置高级接口的配置项
        // 分块上传阈值和分块大小分别设置为 5MB 和 1MB（若不特殊设置，分块上传阈值和分块大小的默认值均为5MB）
        TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
        transferManagerConfiguration.setMultipartUploadThreshold(10 * 1024 * 1024);
        transferManagerConfiguration.setMinimumUploadPartSize(1024 * 1024);
        transferManager.setConfiguration(transferManagerConfiguration);

        PutObjectRequest putObjectRequest = new PutObjectRequest(cosManager.getBucket(), key, file);
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);

        ObjectMetadata objectMetadata = new ObjectMetadata();
        putObjectRequest.withMetadata(objectMetadata);
        String redisKey = VIDEO_UPDATE + key;
        Upload upload = transferManager.upload(putObjectRequest);
        String uploadJson = JSONUtil.toJsonStr(upload);
        stringRedisTemplate.opsForValue().set(redisKey, uploadJson, VIDEO_UPDATE_TTL, TimeUnit.MINUTES);
        UploadResult uploadResult = null;
        try {
            uploadResult = upload.waitForUploadResult();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(uploadResult.getCiUploadResult());
    }

    /**
     * 获取上传进度
     */
    public double showTransferProgress(String key) {
        String update = stringRedisTemplate.opsForValue().get(VIDEO_UPDATE + key);
        Gson gson = new Gson();
        UploadImpl upload = gson.fromJson(update, UploadImpl.class);
        // transfer.isDone() 查询上传是否已经完成
        if (!upload.isDone()) {
            TransferProgress progress = upload.getProgress();
            return progress.getPercentTransferred();
        }
        //完成了返回100;
        return 100.0;
    }

}
